package com.platform.framework.web.service;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.utils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Service("weather")
public class WeatherService {

    private static final Logger log = LoggerFactory.getLogger(WeatherService.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取天气参数
     */
    @PostConstruct
    public void init() throws IOException {
        if(!redisUtil.hasKey("observe")){
            URL url = new URL("http://api.weatherdt.com/common/?area=101120308&type=observe&key=5b442752f46cc6cd3c51ece9ae48e162");
            HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
            uRLConnection.setDoOutput(true);
            uRLConnection.connect();
            InputStream is = uRLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String respJson = "";
            String readLine = null;
            while((readLine =br.readLine()) != null){
                respJson +=readLine;
            }
            JSONObject jsonObject = JSONObject.parseObject(respJson).getJSONObject("observe").getJSONObject("101120308").getJSONObject("1001002");
            redisUtil.set("observe", jsonObject);
            is.close();
            br.close();
            uRLConnection.disconnect();
        }
    }
}
